package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.zIndex
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.sinogrand.elevator.data.models.HomeElevatorItem
import com.sinogrand.elevator.data.models.ElevatorItem
import com.sinogrand.elevator.repository.HomeRepository
import com.sinogrand.elevator.utils.LogTags
import com.sinogrand.elevator.utils.PaginationUtils
import android.util.Log

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ElevatorListScreen(
    onBackClick: () -> Unit,
    onElevatorClick: (ElevatorItem) -> Unit = {}
) {
    val context = LocalContext.current
    val homeRepository = remember { HomeRepository(context) }
    
    var isRefreshing by remember { mutableStateOf(false) }
    var isLoadingMore by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(true) }
    var homeElevatorList by remember { mutableStateOf<List<HomeElevatorItem>>(emptyList()) }
    var canLoadMore by remember { mutableStateOf(true) }
    var currentPage by remember { mutableStateOf(1) }
    var currentPageInfo by remember { mutableStateOf<com.sinogrand.elevator.data.models.PageInfo?>(null) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    
    val listState = rememberLazyListState()
    val pullRefreshState = rememberPullToRefreshState()
    
    // 将HomeElevatorItem转换为ElevatorItem
    val displayElevatorData = remember(homeElevatorList) {
        homeElevatorList.map { homeItem ->
            ElevatorItem(
                id = homeItem.id,
                name = homeItem.name,
                no = "",
                sn = null,
                type = homeItem.type,
                install_type = homeItem.install_type,
                brand = null,
                model = null,
                floors = null,
                unit_price = null,
                start_date = homeItem.start_date,
                end_date = homeItem.end_date,
                details = null,
                status = homeItem.status,
                approval_config = null,
                has_filing = null,
                has_monitoring = null,
                created_at = homeItem.created_at,
                updated_at = homeItem.updated_at,
                imageUrl = null
            )
        }
    }
    
    // 加载数据的函数
    suspend fun loadElevatorData(page: Int = 1, isRefresh: Boolean = false) {
        try {
            Log.d(LogTags.ELEVATOR_LIST, "开始加载电梯数据，页码: $page")
            if (isRefresh) {
                isRefreshing = true
            } else if (page == 1) {
                isLoading = true
            } else {
                isLoadingMore = true
            }
            errorMessage = null

            val result = homeRepository.getHomeElevatorList(page = page, size = 10)
            
            if (result.isSuccess) {
                val data = result.getOrNull()
                if (data != null) {
                    if (isRefresh || page == 1) {
                        homeElevatorList = data.list
                        currentPage = 1
                        currentPageInfo = data.page_info
                        canLoadMore = PaginationUtils.hasNextPage(data.page_info)
                        Log.i(LogTags.ELEVATOR_LIST, "✅ 成功加载电梯数据: ${data.list.size}条，分页信息: page=${data.page_info.page}, size=${data.page_info.size}, total=${data.page_info.total}")
                    } else {
                        homeElevatorList = homeElevatorList + data.list
                        currentPageInfo = data.page_info
                        canLoadMore = PaginationUtils.hasNextPage(data.page_info)
                        Log.i(LogTags.ELEVATOR_LIST, "✅ 成功加载更多电梯数据: ${data.list.size}条，累计: ${homeElevatorList.size}条，分页信息: page=${data.page_info.page}, size=${data.page_info.size}, total=${data.page_info.total}")
                    }
                }
            } else {
                val exception = result.exceptionOrNull()
                Log.e(LogTags.ELEVATOR_LIST, "❌ 加载电梯数据失败: ${exception?.message}")
                errorMessage = "加载失败: ${exception?.message ?: "未知错误"}"
            }
        } catch (e: Exception) {
            Log.e(LogTags.ELEVATOR_LIST, "💥 加载电梯数据异常: ${e.message}", e)
            errorMessage = "网络异常: ${e.message}"
        } finally {
            isLoading = false
            isRefreshing = false
            isLoadingMore = false
        }
    }

    // 初始化数据
    LaunchedEffect(Unit) {
        loadElevatorData(page = 1)
    }

    // 下拉刷新
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            loadElevatorData(page = 1, isRefresh = true)
            pullRefreshState.endRefresh()
        }
    }
    
    // 上拉加载更多
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
            .collect { lastVisibleIndex ->
                if (lastVisibleIndex != null && 
                    lastVisibleIndex >= displayElevatorData.size - 1 && 
                    canLoadMore && 
                    !isLoadingMore &&
                    !isLoading &&
                    displayElevatorData.isNotEmpty()) { // 确保列表不为空
                    currentPage++
                    loadElevatorData(page = currentPage)
                }
            }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = "急需维保电梯",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White,
                    titleContentColor = Color(0xFF1F2937)
                )
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .nestedScroll(pullRefreshState.nestedScrollConnection)
                .background(
                    Brush.verticalGradient(
                        colors = listOf(
                            Color(0xFFF8FAFC),
                            Color(0xFFF1F5F9)
                        )
                    )
                )
        ) {
            LazyColumn(
                state = listState,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 16.dp),
                // verticalArrangement = Arrangement.spacedBy(12.dp),
                // contentPadding = PaddingValues(bottom = AppConstants.TAB_BAR_HEIGHT) // 为TabBar留出空间
            ) {
                // 加载状态 - 只在没有数据时显示
                if (isLoading && displayElevatorData.isEmpty()) {
                    item {
                        LoadingIndicator()
                    }
                }
                
                // 错误信息
                errorMessage?.let { message ->
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = Color(0xFFFEF2F2)
                            ),
                            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                            shape = RoundedCornerShape(12.dp)
                        ) {
                            Text(
                                text = message,
                                fontSize = 14.sp,
                                color = Color(0xFFDC2626),
                                modifier = Modifier.padding(16.dp)
                            )
                        }
                    }
                }
                
                // 电梯列表
                items(
                    count = displayElevatorData.size,
                    key = { index -> displayElevatorData[index].id }
                ) { index ->
                    val elevator = displayElevatorData[index]
                    // 为第一个元素添加顶部间距
                    if (index == 0) {
                        Spacer(modifier = Modifier.height(12.dp))
                    }
                    
                    ElevatorListItem(
                        elevator = elevator,
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onElevatorClick(elevator) }
                    )
                    
                    // 为每个元素后面添加间距（除了最后一个）
                    if (index != displayElevatorData.size - 1) {
                        Spacer(modifier = Modifier.height(12.dp))
                    }
                }
                
                // 加载更多指示器
                if (isLoadingMore) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(24.dp),
                                color = Color(0xFF3B82F6)
                            )
                        }
                    }
                }
                
                // 没有更多数据提示
                if (!canLoadMore && displayElevatorData.isNotEmpty()) {
                    item {
                        Text(
                            text = "没有更多数据了",
                            fontSize = 14.sp,
                            color = Color(0xFF6B7280),
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
            
            // 下拉刷新容器 - 只在需要时显示
            if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
                PullToRefreshContainer(
                    state = pullRefreshState,
                    modifier = Modifier
                        .align(Alignment.TopCenter)
                        .zIndex(1f) // 确保在列表内容之上
                )
            }
        }
    }
}

@Composable
fun ElevatorListItem(
    elevator: ElevatorItem,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .border(
                width = 2.dp,
                color = if (isDateExpired(elevator.end_date ?: "")) Color(0xFFEF4444) else Color(0xFF10B981),
                shape = RoundedCornerShape(12.dp)
            ),
        colors = CardDefaults.cardColors(
            containerColor = if (isDateExpired(elevator.end_date ?: ""))  
                Color(0xFFFEF2F2) 
            else 
                Color(0xFFF0FDF4)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧内容
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Filled.Warning,
                        contentDescription = null,
                        tint = if (isDateExpired(elevator.end_date ?: "")) Color(0xFFEF4444) else Color(0xFF10B981),
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = elevator.name,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "到期时间: ${elevator.end_date ?: "未知"}",
                    fontSize = 14.sp,
                    color = if (isDateExpired(elevator.end_date ?: "")) Color(0xFFDC2626) else Color(0xFF059669),
                    fontWeight = FontWeight.Medium
                )
            }
            
            // 右侧图片（仅当有图片时显示）
            if (elevator.imageUrl != null) {
                Spacer(modifier = Modifier.width(12.dp))
                
                AsyncImage(
                    model = elevator.imageUrl,
                    contentDescription = null,
                    modifier = Modifier
                        .size(70.dp)
                        .clip(RoundedCornerShape(12.dp)),
                    contentScale = ContentScale.Crop
                )
            }
        }
    }
}

@Composable
fun LoadingIndicator() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(32.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            CircularProgressIndicator(
                modifier = Modifier.size(48.dp),
                color = Color(0xFF3B82F6)
            )
            Spacer(modifier = Modifier.height(16.dp))
            Text(
                text = "加载中...",
                fontSize = 16.sp,
                color = Color(0xFF6B7280)
            )
        }
    }
}

